﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System.IO;

public class shapeBlend : MonoBehaviour
{

    public int smoothAmount = 2;
    public string meshName = "test";
    public string savePath = "Assets/Resources/shapes";
    public Material material;

    bool isDrawFinished;

    List<Vector3> pathPoints = new List<Vector3>();
    List<Vector3> actualPoints = new List<Vector3>();

    private GameObject currentShape;


    void Start()
    {
        CreateColliderPlane();
    }
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit, Mathf.Infinity))
            {
                Debug.LogFormat("add pont {0}", hit.point);
                pathPoints.Add(hit.point);
            }
        }
        else if (Input.GetMouseButtonDown(1))
        {
            if (pathPoints.Count > 1)
            {
                pathPoints.Add(pathPoints[0]);
                PathHelper.GetWayPoints(pathPoints.ToArray(), smoothAmount, ref actualPoints);
                isDrawFinished = true;
                print("绘制结束了");

                CreateMesh(actualPoints);

            }
        }

        if (Input.GetKeyDown(KeyCode.S))
        {
            Debug.Log("save");
            SaveMeshData();
        }

        if (Input.GetKeyDown(KeyCode.R))
        {
            Debug.Log("reset");
            Reset();
        }

    }

    private void SaveMeshData()
    {
        MeshData meshData = new MeshData();
        meshData.name = meshName;
        meshData.vecticles = lineverts;
        meshData.triangles = triangleArr;
        string jsonStr = JsonUtility.ToJson(meshData);
        File.WriteAllText(Path.Combine(savePath,meshName),jsonStr);
    }

    private List<Vector3> lineverts;
    int[] triangleArr;
    private void CreateMesh(List<Vector3> linePoints)
    {
        //center
        Vector3 sumVec = Vector3.zero;
        linePoints.ForEach(x =>
        {
            sumVec += x;
        });
        Vector3 centerPoint = sumVec / linePoints.Count;

        //create
        currentShape = new GameObject("shape");
        MeshRenderer mrd = currentShape.AddComponent<MeshRenderer>();
        mrd.material = material;
        MeshFilter mfr = currentShape.AddComponent<MeshFilter>();
        Mesh mesh = mfr.mesh;

        lineverts = new List<Vector3>();
        lineverts.Add(centerPoint);
        linePoints.ForEach(p => lineverts.Add(p));
        print(linePoints.Count);

        triangleArr = new int[3 * linePoints.Count];
        for (int i = 0,tri=0; i < linePoints.Count; i++,tri+=3)
        {
            if (i < linePoints.Count - 1)
            {
                triangleArr[tri] = 0;
                triangleArr[tri + 1] = i + 1;
                triangleArr[tri + 2] = i + 2;
            }
            else if (i == linePoints.Count - 1)
            {
                triangleArr[tri] = 0;
                triangleArr[tri + 1] = i + 1;
                triangleArr[tri + 2] = 1;
            }

        }

        mesh.SetVertices(lineverts);
        mesh.SetTriangles(triangleArr, 0);

    }

    private void Reset()
    {
        pathPoints.Clear();
        actualPoints.Clear();
        isDrawFinished = false;
        Destroy(currentShape);
        lineverts = null;
        triangleArr = null;
    }

    private void OnDrawGizmos()
    {

        if(pathPoints.Count > 1)
        {
            PathHelper.DrawPathHelper(pathPoints.ToArray(),20,Color.yellow);
        }

        Gizmos.color = Color.green;
        if (pathPoints.Count > 1)
        {
            for (int i = 0; i < pathPoints.Count-1; i++)
            {
                Gizmos.DrawLine(pathPoints[i],pathPoints[i+1]);
            }
        }

        if (pathPoints.Count > 0)
        {
            pathPoints.ForEach(x => Gizmos.DrawSphere(x, 0.1f));
        }
    }

    private void CreateColliderPlane()
    {
        GameObject quad = GameObject.CreatePrimitive(PrimitiveType.Quad);
        quad.transform.position = transform.position + Vector3.forward * 10;
        Camera cam = GetComponent<Camera>();
        float height = cam.orthographicSize * 2;
        float width = height * 16 / 9f;
        quad.transform.localScale = new Vector3(width, height, 1);
        quad.GetComponentInChildren<MeshRenderer>().enabled = false;
    }

}
